<?php


namespace app\web\controller;



use app\common\service\CommonService;
use app\common\service\TicketService;
use app\web\constant\CommonConstant;
use app\web\validate\TicketSendValidate;
use think\Db;

class TicketSend extends Auth {


    /**
     * 获取优惠券列表
     */
    public function GetTicketList() {

        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $post = $this->request->post();
            if (empty($post['type'])) {
                $this->result('参数优惠券类型缺少', '', 204);
            }

            $query = Db::name('qt_ticket')
                ->field('id,name')
                ->where('store_id',$userInfo['store_id'])
                ->where("is_delete",CommonConstant::IS_DELETE_NO)
                ->where("type",$post['type']);

            $data = $query->order('id desc')->paginate();
            $this->result('查询成功', $data, 200);
        }else{
            $this->result('无效的请求', '', 204);
        }

    }


    /**
     * 发送优惠券
     */
    public function send () {

        if ($this->request->isPost()) {
            $post = $this->request->post();

            if (empty($post['ticket_id'])) {
                $this->result('缺少参数', '', 204);
            }

            $ticket_data = TicketService::getTicketById($post['ticket_id']);
            if (empty($ticket_data)) {
                $this->result('没有找到优惠券信息', '', 204);
            }

            $viper_user = Db::name('qt_viper_card')->where('mobile',$post['phone'])->find();
            if (empty($viper_user)) {
                $this->result('没有找到手机号对应的会员信息', '', 204);
            }

            $userInfo = $this->userInfo;

            $data = $post;
            $data['store_id'] = $userInfo['store_id'];
            $data['ticket_code'] = CommonService::uniqidNumber(12,'TK');
            $data['creater'] = $data['updater'] = $data['sender'] = $userInfo['id'];
            $data['create_time'] = $data['update_time'] = $data['send_time'] = time();
            $data['is_receive'] = $data['is_use'] = $data['is_delete'] = CommonConstant::IS_DELETE_NO;
            $data['expiration_time'] = strtotime(date("Y-m-d H:i:s",strtotime("+".$ticket_data['term']." day")));

            $validate = new TicketSendValidate();
            if (!$validate->scene('send')->check($data)) {
                $this->result($validate->getError(), '', 204);
            }

            $data['consumption_ewm'] = 'uploads/ticket_send/'.create_ewm(json_encode(['ticket_code'=>$data['ticket_code'],'type'=>1]),'uploads/ticket_send/',$data['ticket_code'].'_1.png');
            $data['collect_ewm'] = 'uploads/ticket_send/'.create_ewm(json_encode(['ticket_code'=>$data['ticket_code'],'type'=>2]),'uploads/ticket_send/',$data['ticket_code'].'_2.png');


            $flag = true;
            for ($i=1; $i<=$post['send_num']; $i++) {
                $data['send_num'] = 1;
                $integralId = Db::name('qt_ticket_send')->insertGetId($data);
                if (!$integralId) {
                    $flag=false;
                }
            }
            if($flag){
                $this->result('添加成功', '', 200);
            }else{
                $this->result('添加失败', '', 204);
            }
        }else{
            $this->result('无效的请求', '', 204);
        }
    }

    /**
     * 票券删除
     *
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function remove () {
        if($this->request->isPost()) {
            $send_id = $this->request->post('send_id');
            if (empty($send_id)) {
                $this->result('优惠券ID不能为空', '', 204);
            }
            $data = TicketService::getTicketSendById($send_id);
            if (!empty($data)) {

                $userInfo = $this->userInfo;
                Db::name('qt_ticket_send')
                    ->update([
                        'id'=>$send_id,
                        'is_delete'=>CommonConstant::IS_DELETE_YES,
                        'deleter'=>$userInfo['id'],
                        'delete_time'=>time()
                    ]);

                $this->result('删除成功', '', 200);
            }else {
                $this->result('没有查询到对应ID的数据', '', 204);
            }
        }

        $this->result('无效的请求', '', 204);

    }


    /**
     * 获取发放优惠券列表
     */
    public function lists() {

        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (empty($post['page']) || empty($post['limit']) || empty($post['is_delete'])) {
                $this->result('缺少参数', '', 204);
            }

            $query = Db::name('qt_ticket_send')
                ->alias('ts')
                ->leftJoin('qt_ticket tk','tk.id = ts.ticket_id')
                ->leftJoin('qt_users u','u.id = ts.updater')
                ->where("ts.is_delete",$post['is_delete']);


            if (isset($post['start_time']) && !empty($post['start_time'])) {
                $startTime = strtotime($post['start_time']);
                $endTime = strtotime($post['end_time']);
                $query->whereBetweenTime('ts.send_time', $startTime, $endTime);
            }

            if (!empty($post['ticket_code'])) {
                $query->where('ts.ticket_code',$post['ticket_code']);
            }

            if (!empty($post['type'])) {
                $query->where('tk.type',$post['type']);
            }

            if (!empty($post['ticket_id'])) {
                $query->where('ts.ticket_id',$post['ticket_id']);
            }

            if (!empty($post['name'])) {
                $query->whereLike('tk.name','%'.$post['name'].'%');
            }

            if (!empty($post['is_use'])) {
                $query->where('ts.is_use',$post['is_use']);
            }
            if (!empty($post['phone'])) {
                $query->where('ts.phone',$post['phone']);
            }

            if (!empty($post['sender'])) {
                $query->where('ts.sender',$post['sender']);
            }

            $count_model = clone $query;
            $all_model = clone $query;

            $data = $query->field('ts.*,u.id as user_id,u.real_name,tk.id as tk_id ,tk.type,tk.name,tk.quota')
                ->order('ts.id desc')->paginate($post['limit'])->each(function ($item) {
                    if (!empty($item['expiration_time'])) {
                        $days = CommonService::getBetweenDayNum(date("Y-m-d", $item['expiration_time']), date("Y-m-d", time()));
                        $item['validity_time'] = $days;
                    }else {
                        $item['validity_time'] = 0;
                    }
                    $item['deleter_name'] = Db::name('qt_users')->where('id',$item['deleter'])->value('real_name') ?? '';
                    $item['sender_name'] = Db::name('qt_users')->where('id',$item['sender'])->value('real_name') ?? '';
                    $item['verifier_name'] = Db::name('qt_users')->where('id',$item['verifier'])->value('real_name') ?? '';

                    $item['consumption_ewm'] =  config('app.site_url') . '/' . $item['consumption_ewm'];
                    $item['collect_ewm'] = config('app.site_url') . '/' . $item['collect_ewm'];
                    return $item;
                });

            $count_data = $count_model->group('tk.id')
                ->column([
                    'tk.id',
                    'tk.name','count(tk.id) as total_num',
                    '0 as use_num',
                    '0 as not_use_num',
                    '0 as delete_num',
                    '0 as overdue_num',
                ],'tk.id');

            $all_data = $all_model->field('ts.*')->select();
            foreach ($count_data as $k => $v) {
                foreach ($all_data as $key => $val){
                    if ($v['id'] == $val['ticket_id']) {
                        if($val['is_use'] == CommonConstant::IS_DELETE_YES) {
                            $v['use_num'] += 1;
                        }
                        if( $val['is_use'] != CommonConstant::IS_DELETE_YES) {
                            $v['not_use_num'] += 1;
                        }
                        if( $val['is_delete'] == CommonConstant::IS_DELETE_YES) {
                            $v['delete_num'] += 1;
                        }
                        if( $val['expiration_time'] < time()) {
                            $v['overdue_num'] += 1;
                        }
                    }
                }
            }

            $this->result('查询成功', ['list'=>$data,'total'=>$count_data], 200);
        }else{
            $this->result('无效的请求', '', 204);
        }

    }
}
